package com.ja.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.context.ContextLoader;

import com.ja.config.WebsiteStateConfig;
import com.ja.domain.KeyWords;
import com.ja.domain.RedPacket;
import com.ja.domain.User;
import com.ja.sevice.IKeyWordsService;
import com.ja.sevice.LiushuiService;
import com.ja.sevice.RedPacketService;
import com.ja.sevice.impl.UserServiceImpl;
import com.ja.util.DateUtil;
import com.ja.util.RedPacketUtil;
/**
 * <style>*{font-size: 14px;font-weight: bold;}div{height:28px;margin-bottom:-23px;}img {position: fixed;bottom: 10px;right: 10px;height: 50px;}span{border: 3px solid blue;color: white;background: blue;display: inline-block;box-shadow: 2px 2px gray;margin: 2px 10px;margin-left: 40px;}l div{font-size:40px;display: inline-block;line-height: 16px;position: absolute;margin-top: -3px;font-weight: lighter;color: red;}p{font-weight: lighter;margin-top: 22px;}l{display: inline-block;width: 80px;text-align: right;color: black;margin-top:10px;}</style><img src="https://a3.qpic.cn/psb?/V13i62Dj12ePbQ/NZmahM6aAmswZqIzVUkRHAvJMKUvnBP*ccASpf*fwec!/m/dF4BAAAAAAAAnull&bo=zwGhAAAAAAADB00!&rf=photolist&t=5"></img><div class="me" style="margin-top:-26px;">
 * <p><b>　描述：</b><!--TODO-->群聊控制层
 * </p><l>INFO<div>☞</div></l><span>文件名：ChatController3.java　　　版本：v1.0
 * </span><br><l>Date<div>☞</div></l><span>2018年3月21日 下午12:02:18
 * </span><br><l>Author<div>☞</div></l><span>Bean
 * </span></div>
 */
@ServerEndpoint("/all")
public class ChatController3{
	
	private RedPacketService redPacketService = (RedPacketService) ContextLoader.getCurrentWebApplicationContext().getBean("redPacketService");
	
	private UserServiceImpl userService = (UserServiceImpl) ContextLoader.getCurrentWebApplicationContext().getBean("userService");
	
	private IKeyWordsService keyWordsService=(IKeyWordsService)ContextLoader.getCurrentWebApplicationContext().getBean("keyWordsService");
	
	private LiushuiService liushuiService=(LiushuiService)ContextLoader.getCurrentWebApplicationContext().getBean("liushuiService");
	
    private static int onlineCount = 0;
    
    private static CopyOnWriteArraySet<ChatController3> webSocketSet = new CopyOnWriteArraySet<ChatController3>();
    
    private static List<String> names= new ArrayList<String>();
    
    static Map<String, Session> map=new HashMap<String, Session>(); //保存建立连接的用户session
    
    private Session session;
    
    private String name;
    
	@Override
	public String toString() {
		return "ChatController3 [name=" + name + "]";
	}

	/**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
	private static boolean count = false;
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        addOnlineCount();           //在线数加1
        if(webSocketSet.size() <= 0) {
        	webSocketSet.add(this);
        }
        this.name= session.getRequestParameterMap().get("name").get(0);//获取本次登录用户的姓名
        for (ChatController3 item : webSocketSet) {
        	if(item.name.equals(this.name)) {
        		count = false;
        		break;
        	}else {
        		/**
        		 * 当if没有匹配上他就会走else 然后一直为true 走到结束还是为true 
        		 * 如果中途有一个匹配上了，就证明有这个用户的存在，那么结束循环，
        		 * 边成false 下面则不添加这个用户，
        		 */
        		count = true;
        	}
		}
        if(count) {
        	webSocketSet.add(this); 
        }
        names.add(this.name);//将本次登录用户的姓名添加到names里面
        map.put(name, session);
//        ChatController3 tr = new ChatController3(); 
//        Thread t=new Thread(tr);
//        if (isFirst) {
//        	isFirst=false;
//        	t.start();
//		}
//        this.run();
    }
     
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1    
    }
     
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
	@OnMessage
    public void onMessage(String message, Session session,HttpServletRequest request) {
		WebsiteStateConfig.configs.get("chatroomFlag");
		if(Integer.parseInt(WebsiteStateConfig.configs.get("chatroomFlag"))==0) {
			return;
		}
    	String messages[]= message.split("k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u");
    	String fromName=messages[0];
    	User user1 = userService.getUserByid(new Integer(fromName.trim()));
    	if(user1.getState() == 2) {
    		return;
    	}
    	String toName=messages[1];
    	String mess=messages[2];
    	Integer redPackId=0;
    	if (mess.contains("BeanRedPackageJa")) {
    		List<KeyWords> keyWords = keyWordsService.findAll();
    		String redPack[]=mess.split("BeanRedPackageJa");
    		String x="";
    		String type="固定红包";
    		String leavingAMessage = redPack[2];
    		for (KeyWords kWs : keyWords) {
				if (redPack[2].contains(kWs.getStr())) {
					leavingAMessage = "恭喜发财,大吉大利";
				}
			}
    		if (redPack[3].contains("普通")) {
    			List<Integer> list=RedPacketUtil.splitRedPackets((int) (Double.parseDouble(redPack[0])*10.0), Integer.parseInt(redPack[1]));
    			x=list.toString().replace("[", "").replace("]", "").replace(" ", "");
    			type="拼手气红包";
    			if ("0".equals(fromName)) {
					userService.updBlance(0,Double.parseDouble(redPack[0]));
				}
			}else {
				if ("0".equals(fromName)) {
					userService.updBlance(0,Double.parseDouble(Integer.parseInt(redPack[1])*Integer.parseInt(redPack[0])+""));
				}
				for (int i = 0; i < Integer.parseInt(redPack[1]); i++) {
					x+=((Integer.parseInt(redPack[0])*10)+",");
				}
				x=x.substring(0, x.length()-1);
			}
    		RedPacket redPacket=new RedPacket(Integer.parseInt(fromName), new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()), type, redPack[0], redPack[1], leavingAMessage, x, 0);
    		redPacketService.insert(redPacket);
    		redPackId = redPacket.getId();
            double amount = 0.00;
    		if (redPack[3].contains("普通")) {
    			amount = Double.parseDouble(redPack[0]);
    		}else {
    			amount = Double.parseDouble(redPack[0])*Double.parseDouble(redPack[1]);
			}
    		User user = userService.getUserByid(Integer.parseInt(fromName));
    		String orderNum = "HB"+DateUtil.DateFormatOrderNum()+user.getId();
    		liushuiService.addActivityRecord(user, orderNum,false, amount, "红包扣款", 1);
		}
    	boolean isFirst=false;
		for (ChatController3 item : webSocketSet) {
			if ("all".equals(toName)) {//群聊
				List<KeyWords> list = keyWordsService.findAll();
				if (!mess.contains("BeanRedPackageJa")&&!isFirst) {
					for (KeyWords keyWords : list) {
						if (mess.contains(keyWords.getStr())) {
							mess = mess.replace(keyWords.getStr(), keyWords.getReplaceStr());
						}
					}
					isFirst=true;
					RedPacket redPacket = new RedPacket();
					redPacket.setUserid(new Integer(fromName.trim()));
					redPacket.setDesc(mess);
					redPacket.setCreattime(DateUtil.getCurrTime());
					redPacketService.saveUserChatRecord(redPacket);
				}
				if (!item.name.equals(fromName)) {
					try {
						if (mess.contains("BeanRedPackageJa")) {
							item.sendMessage(mess+"BeanRedPackageJa"+redPackId+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+fromName);
						}else {
							item.sendMessage(mess+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+fromName);
						}
					} catch (Exception e) {
						continue;
					}
				}else {
					try {
						item.sendMessage("Bean1RedPackageJa"+redPackId);
					} catch (Exception e) {
						continue;
					}
				}
			}
		}
    }
    
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }
    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message){
    	try {
			this.session.getBasicRemote().sendText(message);
		} catch (Exception e) {
		}
    }
    
    public void sendMessageToPeople(String toName,String fromName,String message) throws IOException {
    	this.session.getBasicRemote().sendText(toName+fromName+message);
	}
    
    
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        ChatController3.onlineCount++;
    }
     
    public static synchronized void subOnlineCount() {
        ChatController3.onlineCount--;
    }

}